/*
 * @Author: silence
 * @Date: 2023-07-07 11:38:27
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-12-15 09:11:23
 * @Description: 电站相关请求
 */
import 'package:ems_neutral_app/entities/WarningEntity.dart';
import 'package:sil_base_widget_package/tools/SilUtilsTools.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../../entities/DeviceEntity.dart';
import '../../entities/PowerStationEntity.dart';
import '../../entities/TimeZoneEntity.dart';
import '../ApiUtils.dart';
import '../R.dart';

/**
 * 获取电站信息
 */
Future<R> api_power_station_info(
    {required String deviceId, bool throwException = false}) async {
  Map<String, dynamic> params = Map();
  params['powerId'] = deviceId;
  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, 'api/plant/myPlantResult',
      param: params);

  R r = R.fromData(methodAwait, throwException: throwException,
      handlerData: (map) {
    PowerStationEntity entity = PowerStationEntity();

    if (!SilTools.mapIsEmpty(map)) {
      entity = PowerStationEntity.fromJson(map);
    }

    return entity;
  });

  return r;
}

/**
 * 获取电站基本信息
 */
Future<R> api_power_station_base_info({required String deviceId}) async {
  Map<String, dynamic> params = Map();
  params['powerId'] = deviceId;
  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, 'api/plant/myPlantInfo',
      param: params);

  R r = R.fromData(methodAwait, handlerData: (map) {
    PowerStationEntity entity = PowerStationEntity();
    if (!SilTools.mapIsEmpty(map)) {
      entity = PowerStationEntity.fromJson(map);
    }
    return entity;
  });

  return r;
}

/**
 * 获取电站温度，余额信息
 */
Future<R> api_power_station_temperature({required String deviceId}) async {
  Map<String, dynamic> params = Map();
  params['powerId'] = deviceId;
  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.GetMethod, 'user/canPowerRevenue/getPvTemperature',
      param: params, showErrorToast: false);

  R r = R.fromData(methodAwait, handlerData: (map) {
    PowerStationEntity entity = PowerStationEntity();
    Map resultMap = map as Map;
    if (!SilTools.mapIsEmpty(resultMap)) {
      if (resultMap.containsKey('data')) {
        List list = resultMap['data'];
        // SilEntityLog.log('PowerStationEntity', list.first);
        entity = PowerStationEntity.fromJson(list.first);
      }
    }

    return entity;
  });

  return r;
}

/**
 * 我的电站列表
 */
Future<R> api_power_station_my_list() async {
  Map<String, dynamic> map = Map();

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, 'api/plant/myPlantList',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    List<DeviceEntity> list = [];

    if (!SilTools.listIsEmpty(map)) {
      List records = map as List;
      for (var item in records) {
        DeviceEntity entity = DeviceEntity.fromJson(item);
        list.add(entity);
      }
    }
    return list;
  });

  return r;
}

/**
 * 切换电站
 * powerRecordId 电站id
 * userId 用户id
 */
Future<R> api_power_station_change(
    {required String powerRecordId, String? userId}) async {
  Map<String, dynamic> map = Map();

  if (!SilTools.stringIsEmpty(userId)) {
    map['id'] = userId;
  }
  map['powerRecordId'] = powerRecordId;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PutMethd, 'api/canUser/canUser',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 获取电站设置信息
 * powerRecordId 电站id
 */
Future<R> api_power_station_set_info(
    {required String powerRecordId, String? userId}) async {
  Map<String, dynamic> map = Map();
  map['powerId'] = powerRecordId;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.GetMethod, 'user/canPowerRevenue/queryDevice2',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 保存电站设置 
 */
Future<R> api_power_station_set_save({required Map paramMap}) async {
  Map<String, dynamic> map = Map();
  if (paramMap.containsKey('powerId')) {
    map['powerId'] = paramMap['powerId'];
  }
  if (paramMap.containsKey('isPayPower')) {
    map['isPayPower'] = paramMap['isPayPower'];
  }
  if (paramMap.containsKey('powerSet')) {
    map['powerSet'] = paramMap['powerSet'];
  }
  if (paramMap.containsKey('usePowerSet')) {
    map['usePowerSet'] = paramMap['usePowerSet'];
  }

  if (paramMap.containsKey('powerPrice')) {
    map['powerPrice'] = '${paramMap['powerPrice']}';
  }

  if (paramMap.containsKey('moneyType')) {
    map['moneyType'] = paramMap['moneyType'];
  }

  if (paramMap.containsKey('moneyUnit')) {
    map['moneyUnit'] = paramMap['moneyUnit'];
  }

  if (paramMap.containsKey('eybond_ctrl_112')) {
    map['eybond_ctrl_112'] = paramMap['eybond_ctrl_112'];
  }

  if (paramMap.containsKey('eybond_ctrl_116')) {
    map['eybond_ctrl_116'] = paramMap['eybond_ctrl_116'];
  }

  if (paramMap.containsKey('eybond_ctrl_117')) {
    map['eybond_ctrl_117'] = paramMap['eybond_ctrl_117'];
  }

  if (paramMap.containsKey('eybond_ctrl_118')) {
    map['eybond_ctrl_118'] = paramMap['eybond_ctrl_118'];
  }

  if (paramMap.containsKey('eybond_ctrl_119')) {
    map['eybond_ctrl_119'] = paramMap['eybond_ctrl_119'];
  }

  if (paramMap.containsKey('eybond_ctrl_120')) {
    map['eybond_ctrl_120'] = paramMap['eybond_ctrl_120'];
  }

  if (paramMap.containsKey('eybond_ctrl_121')) {
    map['eybond_ctrl_121'] = paramMap['eybond_ctrl_121'];
  }

  if (paramMap.containsKey('eybond_ctrl_122')) {
    map['eybond_ctrl_122'] = paramMap['eybond_ctrl_122'];
  }

  if (paramMap.containsKey('eybond_ctrl_123')) {
    map['eybond_ctrl_123'] = paramMap['eybond_ctrl_123'];
  }

  if (paramMap.containsKey('automaticSettings')) {
    map['automaticSettings'] = paramMap['automaticSettings'];
  }

  /// 自动充电
  if (paramMap.containsKey('isCheckSoc')) {
    map['checkSoc'] = paramMap['isCheckSoc'];
  }

  /// 放电下限，暂时不使用
  // if (paramMap.containsKey('dischargeLowerLimit')) {
  //   map['dischargeLowerLimit'] = paramMap['dischargeLowerLimit'];
  // }

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, 'api/plant/myPlantSet',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 修改电站
 * psName 电站名称
 * psId   电站id
 */
Future<R> api_power_station_edit(
    {required String psName, required String psId}) async {
  Map<String, dynamic> map = Map();

  map['id'] = psId;
  map['psName'] = psName;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PutMethd, 'api/power/canPowerStation',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 删除电站
 * deveiceId 电站id
 */
Future<R> api_power_station_del({required String deveiceId}) async {
  Map<String, dynamic> map = Map();
  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.DeleteMethd, 'api/power/canPowerStation/${deveiceId}',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 添加电站
 * psName 电站名称（同SN码）
 * snNumber SN码
 * modelSelection 设备型号
 * equipmentSelection 设备类型
 * timeZoneStr 时区
 * timeZone  时区id
 * locationLng 经度
 * locationLat 纬度
 * createMode 1SN创建，0Wifi
 * userId 用户id
 * key 思道尔需要的key
 */
Future<R> api_power_station_add(
    {required String psName,
    required String snNumber,
    required String modelSelection,
    required int equipmentSelection,
    required String timeZoneStr,
    required int timeZone,
    required double locationLng,
    required double locationLat,
    String? userId,
    String? key,
    int createMode = 1}) async {
  Map<String, dynamic> map = Map();

  map['psName'] = psName;
  map['snNumber'] = snNumber;
  map['modelSelection'] = modelSelection;
  map['equipmentSelection'] = equipmentSelection;
  map['timeZoneStr'] = timeZoneStr;
  map['timeZone'] = timeZone;
  map['locationLng'] = locationLng;
  map['locationLat'] = locationLat;
  map['createMode'] = createMode;

  if (!SilUtilsTools.stringIsEmpty(userId)) {
    map['userId'] = userId;
  }

  if (!SilUtilsTools.stringIsEmpty(key)) {
    map['key'] = key;
  }
  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, '/api/plant/addPlant',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 获取时区
 */
Future<R> api_time_zone_list({String? searchContext, int? page}) async {
  Map<String, dynamic> map = Map();

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.GetMethod, '/yizhen/getTimeZoneList?word=',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    List result = map as List;
    List<TimeZoneEntity> list = [];
    if (!SilTools.listIsEmpty(result)) {
      for (var item in result) {
        TimeZoneEntity entity = TimeZoneEntity.fromJson(item);
        list.add(entity);
      }
    }
    return list;
  });

  return r;
}

/**
 * 获取最新电价
 */
Future<R> api_latest_electricity_price() async {
  Map<String, dynamic> map = Map();

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.GetMethod, 'api/electricityPrice/latestElectricityPrice',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 削峰填谷-智能获取充放电时间段
 */
Future<R> api_auto_peak_load_shifting() async {
  Map<String, dynamic> map = Map();

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.GetMethod, 'api/electricityPrice/peakLoadShifting',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 查询我的电站发电-用电量对比
 */
Future<R> api_power_station_plant_chart(
    {required String deviceId, int? year, int? month, int? day}) async {
  Map<String, dynamic> map = Map();
  map['i18n'] = '中国'; // 国际语言
  map['powerId'] = deviceId;

  if (year != null) {
    map['year'] = '$year';
  } else if (month != null) {
    map['month'] = '$month';
  } else if (day != null) {
    map['day'] = '$day';
  }

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, 'api/plant/myPlantChart',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    List list = map;
    List resultList = [];
    if (!SilTools.listIsEmpty(list)) {
      for (var i = 0; i < list.length; i++) {
        Map tempMap = list[i];
        String time = '';
        if (year != null) {
          time = tempMap['time'];
        } else {
          time = '${i + 1}';
        }

        resultList.add({
          'time': time,
          'fadian': tempMap['fadian'],
          'yongdian': tempMap['yongdian']
        });
      }
    }

    return resultList;
  });

  return r;
}

/**
 * 查询实时SOC(电池百分比曲线)
 */
Future<R> api_power_station_soc_chart({required String deviceId}) async {
  Map<String, dynamic> map = Map();
  map['plId'] = deviceId;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, 'api/plant/getSocInfo',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/**
 * 获取故障列表
 * param powerId 电站id
 * param isFinished 是否已完成
 * param page 页码
 */
Future<R> api_fault_list(
    {required powerId, bool isFinished = false, int? page}) async {
  Map<String, dynamic> map = Map();

  if (page != null) {
    map['current'] = page;
  }
  map['size'] = 10;
  map['handleState'] = isFinished ? 1 : 0;
  map['powerId'] = powerId;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.PostMethd, '/api/canFault/page',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    List<WarningEntity> list = [];

    if (map.containsKey('records')) {
      List records = map['records'];
      for (var item in records) {
        WarningEntity entity = WarningEntity.fromJson(item);
        list.add(entity);
      }
    }
    return list;
  });

  return r;
}
